package server;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @ClassName: MyClassLoader
 * @Description: 自定义ClassLoader
 * @Author: Administrator
 * @Date: 2021/9/5 14:20
 */
public final class MyClassLoader extends ClassLoader {

    private String classDir;// 文件目录

    @Override
    public Class<?> findClass(String name) {
        String realPath = classDir + name.replace(".", "/") + ".class";//class文件的真实路径
        byte[] cLassBytes = null;
        Path path = null;

        try {

            path = Paths.get(new URI(realPath));
            cLassBytes = Files.readAllBytes(path);

        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }
        Class clazz = defineClass(name, cLassBytes, 0, cLassBytes.length);//调用父类的defineClass方法
        return clazz;
    }


    public MyClassLoader(String classDir) {
        this.classDir = "file:/".concat(classDir);//拼接 “file:/”前缀
    }
}
